<?php
require_once('../includes/settings.php');
require_once('../includes/functions.php');
require_once('../includes/repository.php');
require_once('../includes/sql.php');
deny_get_request();

if(isset($_REQUEST['action'])){
	if($_REQUEST['action']=='logout'){
		@session_start();
		$_SESSION['user']=NULL;
		header("location: /login.php");
		exit();
	}
}else{
	if(!isset($_POST['code']) || !isset($_POST['email']) || !isset($_POST['password'])){
		_json('{"error":"invalid parameter"}');
		exit();
	}
	@session_start();
	if(!strtolower($_POST['code']) == $_SESSION['security_code']){
		_json('{"error":"invalid validCode"}');
		exit();
	}

	$user = User::get_by_email_and_password($_POST['email'],$_POST['password']);
	Repository::error();
	if($user){
		$_SESSION['user']=$user;
		$user_config = UserConfig::get_by_user_id($user['id']);
		$_SESSION['user_config'] = array(
			'amount_per_day' => $user_config['amount_per_day'], 
			'money' => $user_config['money'],
			'last_learned_at' => $user_config['last_learned_at'] 
		);
		header("location: /course");
		exit();
	}else{
		header("location: /login/1");
	}
}
?>